<?php
namespace Frieza\Modules\Totem\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\model\Totem\TotemConfig;
use Doraemon\model\Totem\TotemTypes;
use Doraemon\service\Totem\TotemService;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Illuminate\Http\Request;
use Encore\Admin\Widgets\Tab;
use Encore\Admin\Widgets\Form;
use Illuminate\Support\MessageBag;
use Doraemon\tools\Log;

class TotemConfigController extends Controller
{
    public function list(Request $request, Content $content)
    {
        $params = $request->input();
        $pageSize = $request->input("per_page", 20);
        $page = $request->input("page", 1);

        $search = [];
        $list = TotemService::getConfigList($page, $pageSize, $search);

        $gridModel = new pGridDataModel($list['list'], $list['total'], [
            'perPage' => $pageSize
        ]);
        $gridList = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->paginate($gridModel->getPerPage());
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->disableCreateButton();
                $grid->disableFilter();
                $grid->column("id", 'ID');
                $grid->column("totem_type_id", '徽章类型')->display(function () {
                    $typeInfo = TotemTypes::getInfoById($this->totem_type_id);
                    return $typeInfo['type_name'];
                });
                $grid->column("totem_action", '触发标识符');
                $grid->column("fact_name", '徽章类名');
                $grid->column("addtime", '创建时间')->display(function () {
                    return date("Y-m-d H:i:s", $this->addtime);
                });
                $grid->column("edittime", '更新时间')->display(function () {
                    return date("Y-m-d H:i:s", $this->edittime);
                });
                $grid->column("conf_status","状态")->editable('select', TotemConfig::CONF_STATUS_DESC);
                $grid->column("admin_id", '操作人员')->display(function () {
                    return "<span style='width:80px;display: inline-block;'>".Admin::user()->find($this->admin_id)->name."</span>";
                });
                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableDelete();
                });
            });

        $tab = new Tab();
        $tab->add('配置列表', $gridList->render(), true);
        $tab->addLink('添加配置', url('admin/totem/config_create'));
        $content->row($tab);
        return $content
            ->header('徽章配置管理')
            ->description(' ')
            ->breadcrumb(['text' => '配置列表']);
    }

    public function create(Request $request, Content $content, $id = 0)
    {
        $row = [];
        if ($id) {
            $row = TotemService::getConfigInfo($id);
            $header = "编辑配置";
        } else {
            $header = "添加配置";
        }
        $tab = new Tab();
        $form = new Form($row);

        if ($id) {
            $form->hidden('id');
        }
        $form->select('totem_type_id', '徽章类型')->options(TotemService::getSelectTypes())->required();
        $form->text('totem_action', '触发标识符')->required();
        $form->text('fact_name', '徽章类名')->required();

        $form->action(url('admin/totem/config_save'));

        $tab->addLink('配置列表', url('admin/totem/config_list'));
        $tab->add($header, $form->render(), true);
        return $content
            ->header('徽章配置管理')
            ->description(' ')
            ->breadcrumb(['text' => $header])
            ->row($tab);
    }

    public function save(Request $request)
    {
        try {
            $params = $request->all();
            unset($params['_token']);

            $result = TotemService::saveConfig($params);
            if ($result) {
                return redirect(url('/admin/totem/config_list'))->with(compact('success'));
            } else {
                $error = new MessageBag([
                    'title' => '操作失败'
                ]);
                return back()->withInput()->with(compact('error'));
            }
        } catch (\Exception $e) {
            Log::debug($e->getMessage());
            $error = new MessageBag([
                'title' => '操作失败,信息:' . $e->getMessage()
            ]);
            return back()->with(compact('error'));
        }
    }

    public function edit(Request $request, $id = 0)
    {
        try {
            $params = $request->all();
            unset($params['_token']);

            $data[$params['name']] = $params['value'];
            $result = TotemService::editConfigStatus($id, $data);

            $code = $result['status'] ? 200 : 400;
            return response()->json($result, $code);
        } catch (\Exception $e) {
            Log::debug($e->getMessage());
            return response()->json([
                'status' => false,
                'message' => "操作失败"
            ], 400);
        }
    }
}